<template>
  <a-modal v-model="visible" :mask="true" footer-hide title="图片裁剪" :styles="{top: '20%'}" :width="options.width" :height="options.height" :transfer="false" @cancel="close" @ok="uploadClick" okText="确认上传">
    <a-row>
      <a-col span="14" :style="{height: options.cropAreaHeight}">
        <vue-cropper
          v-if="visible"
          ref="cropper"
          :img="options.img"
          :info="true"
          :fixed="false"
          :enlarge="options.enlarge"
          :centerBox="true"
          :autoCrop="options.autoCrop"
          :autoCropWidth="options.autoCropWidth"
          :autoCropHeight="options.autoCropHeight"
          :fixedBox="options.fixedBox"
          @realTime="realTime"
        >
        </vue-cropper>
      </a-col>
      <a-col span="10" :style="{height: options.cropAreaHeight}" pull="2">
        <div class="avatar-upload-preview" :style="{width:options.autoCropWidth+'px' ,height:options.autoCropHeight+'px'}">
          <img :src="previews.url" :style="previews.img"/>
        </div>
        <div class="remark">{{options.remark}}</div>
      </a-col>

    </a-row>
    <br>
    <a-row>
      <a-col span="4">
        <a-upload name="file" :beforeUpload="beforeUpload" :showUploadList="false" action="">
          <a-button icon="ios-cloud-upload-outline">选择图片</a-button>
        </a-upload>
      </a-col>
      <a-col span="16">
        <a-button-group>
          <a-button @click="changeScale(1)">放大</a-button>
          <a-button @click="changeScale(-1)">缩小</a-button>
          <a-button @click="rotateLeft">向左转</a-button>
          <a-button @click="rotateRight">向右转</a-button>
        </a-button-group>
      </a-col>
    </a-row>
  </a-modal>
</template>
<script>
  import { VueCropper } from 'vue-cropper'
  import axios from 'axios'
  import Vue from 'vue'

  export default {
    name: 'fUploadCopper',
    components: {
      VueCropper
    },
    props: {
      cropOption: {
        type: [Object],
        default: () => ({
          cropWidth: 200,
          width: '750px',
          height: '300px',
          cropAreaHeight: '300px',
          cropHeight: 200,
          enlarge: 1,
          remark: ''
        })
      }
    },
    data() {
      return {
        visible: false,
        type: 'point',
        id: null,
        confirmLoading: false,
        fileList: [],
        file: null,
        uploading: false,
        options: {
          img: '',
          autoCrop: true,
          autoCropWidth: this.cropOption.cropWidth,
          autoCropHeight: this.cropOption.cropHeight,
          cropAreaHeight: this.cropOption.cropAreaHeight,
          height: this.cropOption.height,
          enlarge: this.cropOption.enlarge,
          width: this.cropOption.width,
          remark: this.cropOption.remark,
          fixedBox: true
        },
        previews: {}
      }
    },
    methods: {

      showModal() {
        this.previews = {}
        this.visible = true
      },
      edit(id) {
        this.visible = true
        this.id = id
        /* 获取原始头像 */
      },
      close() {
        this.previews = {}
        this.id = null
        this.options.img = ''
        this.visible = false
      },
      cancelHandel() {
        this.close()
      },
      changeScale(num) {
        num = num || 1
        this.$refs.cropper.changeScale(num)
      },
      rotateLeft() {
        this.$refs.cropper.rotateLeft()
      },
      rotateRight() {
        this.$refs.cropper.rotateRight()
      },
      beforeUpload(file) {
        const reader = new FileReader()
        // 把Array Buffer转化为blob 如果是base64不需要
        // 转化为base64
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.options.img = reader.result
        }
        this.file = file
        // 转化为blob
        // reader.readAsArrayBuffer(file)

        return false
      },

      // 上传图片（点击上传按钮）
      uploadClick() {
        const me = this
        const formData = new FormData()
        const token = Vue.ls.get('Access-Token')
        // 输出
        if (this.type === 'blob') {
          this.$refs.cropper.getCropBlob((data) => {
            const img = window.URL.createObjectURL(data)
            this.model = true
            this.modelSrc = img
            console.log('file', data)
            const file = new File([data], Date.now() + '.' + data.type.split('/')[1], { type: data.type, lastModified: Date.now() })
            formData.append('file', file)
            formData.append('fileType', 'image')
            axios.post(this.api.file.upload, formData, { contentType: false, processData: false, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': token } }).then(res => {
              me.$emit('handleChange', res.data, file)
              me.visible = false
            })
          })
        } else {
          this.$refs.cropper.getCropData((data) => {
            formData.append('base64Img', data)
            formData.append('file', this.file)
            formData.append('fileType', 'image')
            axios.post(this.api.file.upload, formData, { contentType: false, processData: false, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': token } }).then(res => {
              console.info('cropper', res)
              let files = []
              let fileUrl = res.data.data.url
              let useOss = res.data.data.useOss
              if (useOss) {
                fileUrl = res.data.data.ossSmallPath
              }
              files.push({
                uid: res.data.data.uid,
                name: res.data.data.name,
                url: fileUrl,
                status: res.data.data.status
              })
              if (useOss) {
                me.timer = window.setInterval(function() {
                  let imgObj = new Image()
                  imgObj.src = fileUrl
                  if (imgObj.fileSize > 0 || (imgObj.width > 0 && imgObj.height > 0)) {
                    clearInterval(me.timer)
                    me.$emit('handleSuccess', { file: files[0], fileList: files })
                  }
                }, 1000)
              } else {
                me.$emit('handleSuccess', { file: files[0], fileList: files })
              }
              me.visible = false
            })
          })
        }
      },
      okHandel() {
        const vm = this

        vm.confirmLoading = true
        setTimeout(() => {
          vm.confirmLoading = false
          vm.close()
          vm.$message.success('上传头像成功')
        }, 2000)
      },

      realTime(data) {
        this.previews = data
      }
    }
  }
</script>

<style lang="less" scoped>
  .avatar-upload-preview {
    position: absolute;
    top: 40%;
    transform: translate(50%, -50%);
    box-shadow: 0 0 4px #ccc;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .remark {
    position: absolute;
    top: 70%;
    left: 30%;
    overflow: hidden;

  }
</style>
